package com.kiss.fw.command;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.kiss.fw.dto.AbstractDTO;
import com.kiss.fw.exceptions.CommandException;
import com.kiss.fw.utils.Constants;
import com.kiss.fw.utils.Util;

public final class CommandBroker {
	private static final Logger logger = Logger.getLogger(CommandBroker.class);
	private static Map<String, AbstractCommand> singletonCommands = new HashMap<String, AbstractCommand>();
	
	public static void execute(final String _commandKey, AbstractDTO _dto) throws CommandException {
		AbstractCommand command = singletonCommands.get(_commandKey);
		
		if(command == null) {
			try {
				command = (AbstractCommand)Class.forName(Util.getProperty(Constants.Property.COMMAND_CLASS +_commandKey)).newInstance();
			}
			catch(Exception _exception) {
				Util.handleException(logger, "Error creating command", _exception);
				throw Constants.Exceptions.COMMAND_EXCEPTION;
			}
			
			if(isCommandSingleton(_commandKey)) {
				synchronized(singletonCommands) {
					singletonCommands.put(_commandKey, command);
				}
			}
		}
		
		try {
			command.execute(_dto);
		}
		catch(CommandException _exception) {
			throw _exception;
		}
		catch(Exception _exception) {
			Util.handleException(logger, "Error executing command", _exception);
			throw Constants.Exceptions.COMMAND_EXCEPTION;
		}
	}
	
	private static boolean isCommandSingleton(final String _commandKey) {
		return "true".equals(Util.getProperty(Constants.Property.COMMAND_SINGLETON +_commandKey));
	}
}